package com.jl.service.impl;

import com.jl.mapper.AuthMapper;
import com.jl.model.User;
import com.jl.model.vo.UserVo;
import com.jl.service.AuthService;
import com.jl.service.GetUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
@Transactional
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Resource
    private AuthMapper authMapper;
    @Resource
    private GetUserInfoService getUserInfoServicel;

    @Override
    public User insertUser(User user) {
        User user1 = authMapper.selectUserInfo(user.getOpenId());
        if (user1==null){
            int randomNum = getRandomNum();
            user.setUserRole("3");
            user.setCoin(new BigDecimal(0));
            user.setId(randomNum);
            authMapper.insertUseGeneratedKeys(user);
            return user;
        }else {
            user.setId(user1.getId());
            authMapper.updateByPrimaryKeySelective(user);
            return user1;
        }
    }

    public int getRandomNum(){
        int num = (int) ((Math.random() * 9 + 1) * 10000);
        User user = authMapper.selectByPrimaryKey(num);
        while (user!=null){
            num = getRandomNum();
        }
        return num;
    }

    @Override
    public UserVo selectUserInfo(String openId) {
        User user = authMapper.selectUserInfo(openId);
        UserVo userVo = null;
        if (user!=null){
            userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);
        }
        return userVo;
    }

    @Override
    public User phoneLogin(String phone, String password) {
        UserVo userVo = authMapper.selectUserByPassword(phone,getUserInfoServicel.encrypt(password));
        if (userVo!=null){
            User user = new User();
            BeanUtils.copyProperties(userVo,user);
            return user;
        }
        return null;
    }
}
